package com.gps.misc;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.appengine.utils.AeLoadingCenter;
import com.appengine.utils.GsonUtils;
import com.appengine.utils.LogUtils;
import com.appengine.utils.SavingAndLoadingCenter;
import com.appengine.utils.UIUtils;
import com.appengine.utils.UserUtils;
import com.datatypes.ActivityTracks;
import com.datatypes.Friend;
import com.datatypes.FriendsZone;
import com.datatypes.Log;
import com.datatypes.OfflineLogs;
import com.datatypes.Track;
import com.datatypes.User;
import com.datatypes.UserTracks;
import com.datatypes.listItemData;
import com.facebook.android.Facebook;
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.Adapter;
import com.gps.track.GpsShowMap;
import com.gps.track.GpsTrackingActivityGhost;
import com.sporteamws.MainMenu;
import com.sporteamws.R;
import com.sporteamws.SharedPref;

public class GhostRecord extends Activity implements OnItemClickListener,
		OnCreateContextMenuListener, OnClickListener {

	ArrayList<listItemData> listVals = null;
	User user = null;
	UserTracks userTracks = null;
	String title = "";
	int position = 0;
	EditText newName = null;
	private ListView list;
	private ActivityList adapter;
	private FriendsZone fz = null;
	private ArrayList<listItemData> friends_listVals = null;
	boolean startAct = false;
	boolean intentOn = false;
	LocationManager lm = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ghost_list);
		newName = new EditText(this);
		listVals = new ArrayList<listItemData>();
		String UserStr = getIntent().getExtras().getString("USER");

		user = GsonUtils.ConvertGsonStringToUser(UserStr);
		userTracks = SavingAndLoadingCenter.loadUserTracks(
				user.GetFacebookID(), this);
		for (Track t : userTracks.getTracksList()) {
			listVals.add(new listItemData(t));
		}

		list = (ListView) findViewById(R.id.list_of_ghost);
		adapter = new ActivityList(this, listVals);
		list.setAdapter(adapter);
		list.setOnItemClickListener(this);
		list.setOnCreateContextMenuListener(this);

		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		title = listVals.get(info.position).getTrack().getName();

		position = info.position;
		menu.setHeaderTitle(title);
		menu.add("Show track");
		menu.add("Delete");
		menu.add("Rename");
		menu.add("Send Track");
		if (!listVals.get(info.position).getTrack().isSynced()) {
			menu.add("Post on Facebook").setIcon(R.drawable.facebook_icon_post);
		}

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		String itemName = "" + item.getTitle();
		removeDialog(0);

		if (itemName.equals("Delete")) {
			showDialog(0);
		} else if (itemName.equals("Rename")) {
			newName.setText(title);
			showDialog(1);
		} else if (itemName.equals("Send Track")) {
			showDialog(2);
		} else if (itemName.equals("Show track")) {
			Intent intent = new Intent(this, GpsShowMap.class);
			Bundle bundle = new Bundle();
			String trackStr = GsonUtils.ConvertTrackToGsonString(userTracks
					.getTrack(position));
			bundle.putString("GHOST_TRACK", trackStr);
			bundle.putString("USER", getIntent().getExtras().getString("USER"));
			intent.putExtras(bundle);

			SharedPref.returnToMainMenu = false;
			
			startActivity(intent);
		} else if (itemName.equals("Post on Facebook")) {
			userTracks.getTrack(position).setSynced(true);
			SavingAndLoadingCenter.saveUserTracks(user.GetFacebookID(),
					userTracks, GhostRecord.this);
			AeLoadingCenter.PostTrackOnFB(new Facebook(
					SharedPref.facebook_appID), userTracks.getTrack(position),
					this);

		} else
			return false;

		return super.onContextItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Builder builder = null;

		if (id == 0) {
			builder = new Builder(this);
			builder.setTitle("Delete track");
			builder.setIcon(android.R.drawable.ic_delete);
			builder.setNegativeButton("cancel", null);
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							for (listItemData lit : listVals) {
								if (lit.getTrack().getName().equals(title)) {
									listVals.remove(lit);
									break;
								}
							}
							adapter.notifyDataSetChanged();
							boolean isDelete = UserUtils.DeleteTrack(userTracks
									.getTrack(position).getDate(), user
									.GetFacebookID());
							if (!isDelete) {
								OfflineLogs oll = SavingAndLoadingCenter
										.loadOfflineLogs(user.GetFacebookID(),
												GhostRecord.this);
								oll.addLog(new Log(userTracks
										.getTrack(position).getDate(), false));
								SavingAndLoadingCenter.saveOfflineLogs(
										user.GetFacebookID(), oll,
										GhostRecord.this);
							}

							userTracks.deleteTrack(position, user);
							SavingAndLoadingCenter.saveUserTracks(
									user.GetFacebookID(), userTracks,
									GhostRecord.this);
						}
					});
			AlertDialog dialog = builder.create();
			dialog.setMessage("Are you shure you want to delete " + title
					+ " track?");
			return dialog;
		} else if (id == 1) {
			builder = new Builder(this);
			builder.setTitle("Rename track");
			builder.setIcon(android.R.drawable.ic_menu_edit);

			newName = new EditText(this);
			newName.setText(title);
			builder.setView(newName);
			builder.setNegativeButton("cancel", null);
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							String newNameSTR = newName.getText().toString();

							boolean isSynced = UserUtils.RenameTrack(
									user.GetFacebookID(),
									userTracks.getTrack(position).getDate(),
									newNameSTR);

							userTracks.setTrackName(position, newNameSTR, user);
							if (!isSynced) {
								OfflineLogs oll = SavingAndLoadingCenter
										.loadOfflineLogs(user.GetFacebookID(),
												GhostRecord.this);
								oll.addLog(new Log(userTracks
										.getTrack(position).getDate(), true));
								SavingAndLoadingCenter.saveOfflineLogs(
										user.GetFacebookID(), oll,
										GhostRecord.this);
							}
							adapter.notifyDataSetChanged();
							SavingAndLoadingCenter.saveUserTracks(
									user.GetFacebookID(), userTracks,
									GhostRecord.this);

						}
					});
			AlertDialog dialog = builder.create();
			return dialog;
		} else if (id == 2) {
			builder = new Builder(this);
			builder.setTitle("Send Track");
			builder.setIcon(android.R.drawable.ic_menu_send);
			friends_listVals = new ArrayList<listItemData>();
			fz = SavingAndLoadingCenter.loadFriendsZone(user.GetFacebookID(),
					this);
			for (Friend f : fz.getFriends()) {
				if (!f.isInActivity())
					friends_listVals.add(new listItemData(f));
			}
			AlertDialog dialog = null;
			if (!friends_listVals.isEmpty()) {
				ActivityList adapter = new ActivityList(this, friends_listVals);
				builder.setAdapter(adapter, this);
				dialog = builder.create();
			} else {
				builder.setNegativeButton("cancel", null);
				builder.setPositiveButton("POST", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						AeLoadingCenter.PostLonelyStatusOnFB(new Facebook(
								SharedPref.facebook_appID), GhostRecord.this);
					}
				}).setIcon(R.drawable.facebook_icon_post);
				dialog = builder.create();
				dialog.setMessage("It seems that you don't have available friends to create an activity with, why won't you invite some?");
			}
			return dialog;
		} else
			return null;

	}

	@Override
	protected void onPause() {
		super.onPause();
		startAct = true;

		if (!this.isFinishing()) {
			if (!intentOn)
				lm.removeUpdates(SharedPref.lb);
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!intentOn)
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
					SharedPref.lb);
		else
			intentOn = false;

		if (SharedPref.returnToMainMenu && startAct)
			finish();
		else
			SharedPref.returnToMainMenu = true;
	}

	public void onItemClick(AdapterView<?> l, View v, int position, long id) {
		Intent intent = new Intent(this, GpsTrackingActivityGhost.class);
		Bundle bundle = new Bundle();

		String trackStr = GsonUtils.ConvertTrackToGsonString(userTracks
				.getTrack(position));
		bundle.putString("GHOST_TRACK", trackStr);
		bundle.putBoolean("IGHOST", true);
		bundle.putString("USER", getIntent().getExtras().getString("USER"));
		intent.putExtras(bundle);
		
		intentOn = true;
		
		startActivity(intent);

	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		Friend f = friends_listVals.get(which).getFriend();
		com.datatypes.Activity activity = new com.datatypes.Activity(
				userTracks.getTrack(position), user.GetFacebookID(),
				f.getFbID(), user.GetFirstName() + " " + user.GetLastName(),
				f.getName());
		AeLoadingCenter.SendActivity(activity, this);
		ActivityTracks at = SavingAndLoadingCenter.loadActivityTracks(
				user.GetFacebookID(), this);
		fz.getFriend(f.getFbID()).setInActivity(true);
		SavingAndLoadingCenter.saveFriendsZone(user.GetFacebookID(), fz, this);
		at.addActivity(activity, user);
		SavingAndLoadingCenter.saveActivityTracks(user.GetFacebookID(), at,
				this);
		removeDialog(2);
	}
}
